package com.innovation.chengzhangriji.ui.widget;

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.widget.TextView;

import com.innovation.chengzhangriji.Config;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiTextView extends TextView {

    private CharSequence content;

    public EmojiTextView(Context context) {
        super(context);
    }

    public EmojiTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public EmojiTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        content = "";
        if (!TextUtils.isEmpty(text)) {
            text = change(text, Config.EMOJIS_P);
            content = text;
        }
        super.setText(text, type);
    }

    @Override
    public CharSequence getText() {
        return content;
    }

    private SpannableStringBuilder change(CharSequence text, int[] emojis) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        for (int i = 0; i < emojis.length; i++) {
            Pattern pattern = Pattern.compile(getContext().getResources().getString(emojis[i]));
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                builder.setSpan(new ImageSpan(getContext(), Config.EMOJIS_DRAWABLE[i]), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        // TODO 变化二维码
        Pattern pattern = Pattern.compile("\\[二维码\\]");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            builder.setSpan(new ImageSpan(getContext(), Config.EMOJI_QRCODE_DRAWABLE), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return builder;
    }
}
